package tv.scolopender.adapter;

import java.util.ArrayList;

import tv.scolopender.R;
import tv.scolopender.activity.CommentActivity;
import tv.scolopender.application.ScoloApp;
import tv.scolopender.json.FavouriteJSON;
import tv.scolopender.model.Scolo;
import tv.scolopender.model.User;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.provider.Settings.Secure;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;

public class ScoloArrayAdapter extends ArrayAdapter<Scolo> {
	private final Context context;
	private final ArrayList<Scolo> scolos;

	public ScoloArrayAdapter(Context context, int textViewResourceId,
			ArrayList<Scolo> scolos) {
		super(context, textViewResourceId, scolos);
		this.context = context;
		this.scolos = scolos;
	}

	public ScoloArrayAdapter(Context context, int textViewResourceId) {
		this(context, textViewResourceId, new ArrayList<Scolo>());
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View rowView = inflater.inflate(R.layout.listitem_scolo, parent, false);
		TextView text = (TextView) rowView.findViewById(R.id.scoloText);
		RatingBar rating = (RatingBar) rowView.findViewById(R.id.rating);
		Button comment = (Button) rowView.findViewById(R.id.comment);
		Button favorite = (Button) rowView.findViewById(R.id.favorite);
		text.setText(scolos.get(position).getText());
		rating.setRating((float) scolos.get(position).getRating());

		comment.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ScoloApp scoloApp = (ScoloApp) context.getApplicationContext();
				scoloApp.setSelectedScolo(scolos.get(position));

				Activity activity = (Activity) context;
				Intent i = new Intent(activity, CommentActivity.class);
				activity.startActivity(i);
			}
		});

		favorite.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				System.out.println("favorite-clicked");
				new AsyncTask<Void, Void, Void>() {
					@Override
					protected Void doInBackground(Void... params) {
						Activity activity = (Activity) context;
						User user = new User(Secure.getString(
								activity.getContentResolver(),
								Secure.ANDROID_ID));
						System.out.println("insert favourite");
						FavouriteJSON.insertFavourite(scolos.get(position),
								user);
						return null;
					}
				}.execute();
			}
		});
		return rowView;
	}
}
